package repository;

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleOwner;
import android.util.Log;

import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.AutoDisposeConverter;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;

public class BaseRepository implements LifecycleRepository {

    private LifecycleOwner lifecycleOwner;


    public void setLifecycleOwner(LifecycleOwner lifecycleOwner) {
        this.lifecycleOwner = lifecycleOwner;
    }

    @Override
    public void onCreate(LifecycleOwner owner) {
        this.lifecycleOwner=owner;
    }

    @Override
    public void onDestroy(LifecycleOwner owner) {
         owner.getLifecycle().removeObserver(this);
    }

    @Override
    public void onLifecycleChanged(LifecycleOwner owner, Lifecycle.Event event) {
    }

    protected <T> AutoDisposeConverter<T> bindLifecycle() {
        if (null == lifecycleOwner){
            throw new NullPointerException("lifecycleOwner == null");
        }
        return bindLifecycle(lifecycleOwner);
    }

    public  <T> AutoDisposeConverter<T> bindLifecycle(LifecycleOwner lifecycleOwner) {
        return AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(lifecycleOwner)
        );
    }
}
